package org.springframework.amqp.tutorials.rabbitmq_topics.mq;

import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.concurrent.atomic.AtomicInteger;

public class Tut5Sender {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private TopicExchange topicExchange;
    AtomicInteger index = new AtomicInteger(0);
    AtomicInteger dots = new AtomicInteger(0);
    AtomicInteger count = new AtomicInteger(0);

    // 1,2#1,2#1#2#2#null
    private final String[] routingKeys = {
            "quick.orange.rabbit", "lazy.orange.elephant",
            "quick.orange.fox", "lazy.brown.fox",
            "lazy.pink.rabbit", "quick.brown.fox"
    };

    @Scheduled(fixedDelay = 1000, initialDelay = 500)
    public void send() {
        StringBuilder builder = new StringBuilder("Hello to ");
        String routingKey = routingKeys[index.get()];
        if (index.incrementAndGet() == routingKeys.length) {
            index.set(0);
        }
        builder.append(routingKey).append(' ');

        if (dots.incrementAndGet() == 4) {
            dots.set(1);
        }
        for (int i = 0; i < dots.get(); i++) {
            builder.append('.');
        }

        builder.append(count.incrementAndGet());
        String message = builder.toString();
        rabbitTemplate.convertAndSend(topicExchange.getName(), routingKey, message);
        System.out.println(" [x] Sent '" + message + "'");
    }
}
